<?php
namespace Index\Controller;
use Think\Controller;
class LoginController extends Controller {
    public function indexAction()
    {
        if(!empty($_SESSION['uid'])){
            $this->error('你已经登录','',1);
        }else{
            if (IS_POST) {
                $username = I('post.userName');
                $password = md5(I('post.password'));

                $Model = M();
                $isName = $Model->query("select groupId,username,id,face from user where username ='{$username}'  and password ='{$password}'");
                $isMail = $Model->query("select groupId,username,id,face from user where email ='{$username}'  and password ='{$password}'");
                $isMobile = $Model->query("select groupId,username,id,face from user where phone ='{$username}'  and password ='{$password}'");
                if ($isName[0]['gid'] == 3 || $isMail[0]['gid'] == 3 || $isMobile[0]['gid'] == 3) {
                    $this->error('你已被管理设置权限，无法登录', '', 2);
                }
                if (empty($isName) && empty($isMail) && empty($isMobile)) {
                    $this->error('用户名或密码错误', '', 2);
                } else {
                    if(!empty($isName)){
                        $userInfo =$isName[0];
                    }elseif(!empty($isMail)){
                        $userInfo =$isMail[0];
                    }else{
                        $userInfo =$isMobile[0];
                    }
                    $_SESSION['username'] = $userInfo['username'];
                    $_SESSION['uid'] = $userInfo['id'];
                    $_SESSION['gid'] = $userInfo['groupId'];
                    $_SESSION['face'] = $userInfo['face'];
                    $loginTime = time();
                    $Model->execute("update user set loginTime = '{$loginTime}' where id ='{$_SESSION['uid']}'");
    //            session_start();
    //            setcookie(session_name(),session_id(),time()+60);

                    $this->success('登录成功', U("Index/Index/index"), 1);
                }
            }else{
                $this->display('index');
            }
        }

        
    }

    //退出
    public function logoutAction(){
      // $Model = M();
      // $login_time = $Model->query("select login_time from user where id ='{$_SESSION['uid']}'");

      // $logout_time = time();
      // $online_time = $logout_time - $login_time[0]['login_time'];
      // $oldtime = $Model->query("select online_time from user where id ='{$_SESSION['uid']}'");

      // $online_time = $online_time + $oldtime[0]['online_time'];
      // $Model->execute("update user set logout_time = '{$logout_time}', online_time = '{$online_time}' where id ='{$_SESSION['uid']}'");

      session_unset();
      session_destroy();
      $this->success('退出成功',U("Index/Index/index"),1);
   }
}